#include "musiclist.h"
#include<QMimeDatabase>
#include<QMimeType>
#include<QDebug>
#include<QSqlQuery>
#include<QSqlError>

MusicList::MusicList()
{

}

void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
    for(auto musicUrl:urls)
    {
        QString musicPath=musicUrl.toLocalFile();
        if(musicPaths.contains(musicPath))continue;
        musicPaths.insert(musicPath);

        QMimeDatabase database;
        QMimeType mimeType=database.mimeTypeForFile(musicUrl.toLocalFile());
        QString mime=mimeType.name();
        if(mime=="audio/mpeg"||mime=="audio/flac"||mime=="audio/wav")
        {
            Music music(musicUrl);
            musicList.push_back(music);
        }
    }
}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

iterator MusicList::findMusicById(QString musicId)
{
    for(auto it=musicList.begin();it<musicList.end();it++)
    {
        if(musicId==it->getMusicId())return it;
    }
    return musicList.end();
}

void MusicList::writeToDB()
{
    for(auto music:musicList)
    {
        music.writeMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("select musicId, musicName, musicSinger, albumName, duration, musicUrl, isLike, isHistory from musicInfo");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"查询失败"<<query.lastError().text();
        return;
    }
    qDebug()<<"查询成功";
    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicAlbum(query.value(3).toString());
        music.setDuration(query.value(4).toLongLong());
        music.setMusicUrl("file:///"+query.value(5).toString());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        musicList.push_back(music);
        musicPaths.insert(music.getMusicUrl().toLocalFile());
    }
}


